package com.carrot.gateway.filter;

import com.carrot.gateway.filter.handler.auth.AuthApiVersionHandlerFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器
 */

@AllArgsConstructor
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthApiVersionHandlerFactory authApiVersionHandlerFactory;

    private final static String PATH_SYMBOL = "/";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest sourceRequest = exchange.getRequest();
        String path = sourceRequest.getPath().toString();

        String[] pathParam = this.getServiceNameApiVersionForPath(path);
        String serviceName = pathParam[0];
        String apiVersion = pathParam[1];
        //按照api版本获取认证器
        return authApiVersionHandlerFactory.getHandlerByApiVersion(apiVersion)
                .authCheck(exchange, chain, serviceName);
    }


    /**
     * 从 path 中获取service name与api version
     *
     * @param path
     * @return
     */
    private String[] getServiceNameApiVersionForPath(String path) {
        String[] result = new String[2];
        String[] paths = path.split(PATH_SYMBOL);
        if (path.startsWith(PATH_SYMBOL) && paths.length >= 4) {
            result[0] = paths[1];
            result[1] = paths[3];
        } else if (paths.length >= 3) {
            result[0] = paths[0];
            result[1] = paths[2];
        }
        return result;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
